package com.example.train_operate.util;

import com.example.train_operate.constants.YunXinConstants;
import com.example.train_operate.dto.DynamicTokenDTO;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

public class YunXinTokenUtil {


    /**
     * 获取云信token
     * @param channelName 频道名称
     * @param uid 用户id
     * @return
     */
    public static String getToken(String channelName, long uid){
        long curTime = System.currentTimeMillis();
        try {
            return getTokenWithCurrentTime(channelName, uid, YunXinConstants.DEFAULT_TTL_SEC, curTime);
        } catch (Exception e){
            return null;
        }
    }

    /**
     * 根据当前时间获取token
     * @param channelName
     * @param uid
     * @param defaultTtlSec
     * @param curTime
     * @return
     * @throws Exception
     */
    private static String getTokenWithCurrentTime(String channelName, long uid, Integer defaultTtlSec, long curTime) throws Exception{
        DynamicTokenDTO dynamicTokenDTO = new DynamicTokenDTO();
        dynamicTokenDTO.setSignature(sha1(String.format("%s%d%d%d%s%s", YunXinConstants.APP_KEY, uid, curTime, defaultTtlSec, channelName, YunXinConstants.APP_SECRET)));
        dynamicTokenDTO.setCurTime(curTime);
        dynamicTokenDTO.setTtl(defaultTtlSec);
        ObjectMapper objectMapper = new ObjectMapper();
        String signature = objectMapper.writeValueAsString(dynamicTokenDTO);
        return Base64.getEncoder().encodeToString(signature.getBytes(StandardCharsets.UTF_8));
    }

    private static String sha1(String input) throws NoSuchAlgorithmException{
        MessageDigest mDigest = MessageDigest.getInstance("SHA-1");
        byte[] result = mDigest.digest(input.getBytes(StandardCharsets.UTF_8));
        StringBuilder sb = new StringBuilder();
        for(byte b : result){
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }























}
